package session

import (
	"api-gateway-core/common"
	"api-gateway-core/datasource"
	"context"
	"errors"
	hessian "github.com/apache/dubbo-go-hessian2"
)

type GatewaySession struct {
	configuration *common.Configuration
	//用来从configuration获取statement
	key        string
	Datasource *datasource.Datasource
}

func NewGatewaySession(configuration *common.Configuration, key string, datasource *datasource.Datasource) *GatewaySession {
	return &GatewaySession{configuration: configuration, key: key, Datasource: datasource}
}

// 通过泛化调用获取结果
func (this *GatewaySession) GetResult(InfoMap map[string]any) (any, error) {
	//1. 获取连接方式
	connection, err := this.Datasource.GetConnection()
	if err != nil {
		return nil, errors.New("获取连接方式错误：" + err.Error())
	}
	//2. 获取服务信息
	httpStatement := this.configuration.GetStatement(this.key)
	//3. 执行泛化调用
	resp, err := connection.Execute(
		context.Background(),
		httpStatement.MethodName,
		[]string{httpStatement.ParameterType},
		toHessianObject(common.IsSimpleType(httpStatement.ParameterType), InfoMap))
	return resp, err
}

// 判断是否为基本类型
func toHessianObject(flag bool, InfoMap map[string]any) []hessian.Object {
	if !flag {
		return []hessian.Object{InfoMap}
	}
	// 是基本类型 创建一个切片来存储所有的值
	values := make([]hessian.Object, 0, len(InfoMap))
	for _, value := range InfoMap {
		values = append(values, value)
	}
	return values
}
